#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->radioButtonHide->setHidden(true);
    m_bScrollBarStoped=true;


    if (FreshtestID())
        qDebug()<<"fresh sucess.";
    else
        qDebug()<<"fresh false.";


    teststyle_model=new QSqlQueryModel();
    teststyle_model->setQuery("select teststyle,ID from teststyle");
    ui->combo_teststyle->setModel(teststyle_model);

    subject_model=new QSqlQueryModel();
    subject_model->setQuery("select subject,ID from subject");
    ui->combo_subject->setModel(subject_model);
    ui->combo_subject->setModelColumn(0);

    this->ShowQuestion(m_iRecordCurrentID);
    ui->horizontalScrollBar->setMaximum(m_iRecordAmount);
    ui->lblNumber->setText(QString("%1").arg(ui->horizontalScrollBar->minimum()));



}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::FreshtestID()
{
    m_query=new QSqlQuery("SELECT ID from test");
    if(!m_query->exec())
    {
        qDebug()<<"failed"<<m_query->lastError();
    }
    else
    {
        qDebug()<<"[load ok]\n"<<m_query->lastError();

    if (m_query->next())
        {
          if (m_query->isNull(0) == false)
                {
                    m_iRecordCurrentID=m_query->value(0).toInt();
                    //qDebug()<<"init value"<<m_query->value(0).toInt();
                    m_query->last();
                    m_iRecordAmount=m_query->at()+1;
                }
          else
              return false;

        }
    }
    return true;

}

void MainWindow::on_actionLoadQuestion_triggered()
{

}

void MainWindow::on_actionQuestionImportImage_triggered()
{
    QString filename = QFileDialog::getOpenFileName(
        this,
        "Open Document",
        QDir::currentPath(),
        "All files(*.*)");
                //"Document files (*.doc *.rtf);;All files(*.*)");
     if (!filename.isNull()) { //用户选择了文件
        // 处理文件
        //QMessageBox::information(this, "Document", filename, QMessageBox::Ok | QMessageBox::Cancel);
        //return;
     } else // 用户取消选择
        QMessageBox::information(this, "Document", "No document", QMessageBox::Ok | QMessageBox::Cancel);

    //ui->graphicsView->
     //QImage imagefile;
     //QTextImageFormat imageFormat;   //保存图片格式对象
     //    imageFormat.setName(filename);
     //    QTextCursor cursor;                         //编辑指针标
     //    cursor.insertImage(imageFormat);   //通过编辑指针
     ui->textEdit->append("<img src='"+filename+"'>");

}

void MainWindow::on_actionOptionsImportImage_triggered()
{
    QString filename = QFileDialog::getOpenFileName(
        this,
        "Open Document",
        QDir::currentPath(),
        "All files(*.*)");
                //"Document files (*.doc *.rtf);;All files(*.*)");
     if (!filename.isNull()) { //用户选择了文件
        // 处理文件
        //QMessageBox::information(this, "Document", filename, QMessageBox::Ok | QMessageBox::Cancel);
        //return;
     } else // 用户取消选择
        QMessageBox::information(this, "Document", "No document", QMessageBox::Ok | QMessageBox::Cancel);

    //ui->graphicsView->
     //QImage imagefile;
     //QTextImageFormat imageFormat;   //保存图片格式对象
     //    imageFormat.setName(filename);
     //    QTextCursor cursor;                         //编辑指针标
     //    cursor.insertImage(imageFormat);   //通过编辑指针
     ui->textEditOptions->append("<img src='"+filename+"'>");


}


void MainWindow::on_actionUpdateItem_triggered()
{

    QSqlQuery query;
    //if (ui->labelquestion->pixmap()->isNull() == false)
    //  {
        QByteArray bytes_question,bytes_options;
        QBuffer buffer_question(&bytes_question),buffer_options(&bytes_options);
        buffer_question.open(QIODevice::WriteOnly);
        buffer_options.open(QIODevice::WriteOnly);
     //   ui->labelquestion->pixmap()->save(&buffer_question, "PNG");
    //    ui->labeloptions->pixmap()->save(&buffer_options, "PNG");
    //    QString fileName("E:/Users/henry/Documents/qt job/testbase/output.odt");

        QTextDocumentWriter writer_question(&buffer_question,"odf");
        QTextDocumentWriter writer_options(&buffer_options,"odf");
        //writer.setFormat("odf"); // same as writer.setFormat("ODF");
        writer_question.write(ui->textEdit->document());
        writer_options.write(ui->textEditOptions->document());
        QVariant var_question(bytes_question),var_options(bytes_options);
           //if (success)
           //    textEdit->document()->setModified(false);
           //return success;



        //QString sql = "insert into test(question,options) values(?,?)";
        //QString sql = "insert into test(question,options) values(?,?)";
        query.prepare(QString("update test set question=?,options=?,subjectID=%1,teststyleID=%2 where id=%3")
                      .arg(m_subjectID)
                      .arg(m_teststyleID)
                      .arg(m_iRecordCurrentID));
        //query.addBindValue(100);
        query.addBindValue(var_question);
        query.addBindValue(var_options);

        if(!query.exec())
        {
        printf("[insert error]");
//        printf(query.lastError().text().toLocal8Bit().data());
        printf("\n");
        }
        else
        {
        printf("[insert ok]\n");
        }
        //SELECT LAST_INSERT_rowID() as rowid
        //query.exec(QString("UPDATE profile SET photo = 0x%1 WHERE ID = %2").arg(out).arg(iProfileId));

        ui->statusBar->showMessage(tr("File saved"), 2000);

}




void MainWindow::on_actionLoadOptions_triggered()
{
/*    QString filename = QFileDialog::getOpenFileName(
        this,
        "Open Document",
        QDir::currentPath(),
        "All files(*.*)");
                //"Document files (*.doc *.rtf);;All files(*.*)");
     if (!filename.isNull()) { //用户选择了文件
        // 处理文件
        //QMessageBox::information(this, "Document", filename, QMessageBox::Ok | QMessageBox::Cancel);
        //return;
     } else // 用户取消选择
        QMessageBox::information(this, "Document", "No document", QMessageBox::Ok | QMessageBox::Cancel);

    //ui->graphicsView->
     //QImage imagefile;
     //QPixmap pm(filename);

     //ui->labeloptions->resize(pm.size());
     //ui->labeloptions->setScaledContents(true);


     //ui->labeloptions->setPixmap(pm.scaled(ui->labeloptions->size()));
     //app.setMainWidget(label);
     //ui->labeloptions->show();
     */
    //QString fileName("E:/Users/henry/Documents/qt job/Tools_OpenDocument_Editor/sample.odt");
    QString fileName("E:/Users/henry/Documents/qt job/testbase/output.odt");

    QFile f(fileName);
    if (!f.open(QIODevice::ReadOnly)) {
            qDebug() << "Error: could not open database sql file: " + fileName << endl;
            exit(1);
        }
    QByteArray in = f.readAll();
/*
    force = new PushDoc(this);
    Ooo = new OOReader(in);

    Ooo->moveToThread(force);
    connect(force, SIGNAL(started()),Ooo,SLOT(readbuffer()));
    connect(Ooo, SIGNAL(ready()), this, SLOT(drawDoc()));
    //connect(Ooo, SIGNAL(statusRead(int,int)), this, SLOT(onRead(int,int)));
    force->start();
*/
}

void MainWindow::ShowQuestion(int QuestionID)
{
    if (QuestionID<0)
    {
        //ui->labelquestion->setText("database empty");
        //ui->labeloptions->setText("database empty");
        ui->textEdit->setText("");
        return;
    }
    QSqlQuery query(QString("SELECT ID,QUESTION,OPTIONS,ANSWER,subjectID,teststyleID from test WHERE ID=%1")
                            .arg(QuestionID));
    qDebug()<<"qestionid"<<QuestionID;
    if(!query.exec())
    {
    qDebug()<<"[load error]";
    }
    else
    {
        if (query.next())
        {

                  QByteArray byteQuestion = query.value(1).toByteArray();
                  forceQuestion = new PushDoc(this);
                  Ooo = new OOReader(byteQuestion);
                  Ooo->moveToThread(forceQuestion);
                  connect(forceQuestion, SIGNAL(started()),Ooo,SLOT(readbuffer()));
                  connect(Ooo, SIGNAL(ready()), this, SLOT(drawDoc()));
                  //connect(Ooo, SIGNAL(statusRead(int,int)), this, SLOT(onRead(int,int)));
                  forceQuestion->start();

                  QByteArray byteOptions = query.value(2).toByteArray();
                  forceOptions = new PushDoc(this);
                  OOoptions = new OOReader(byteOptions);
                  OOoptions->moveToThread(forceOptions);
                  connect(forceOptions, SIGNAL(started()),OOoptions,SLOT(readbuffer()));
                  connect(OOoptions, SIGNAL(ready()), this, SLOT(drawOptions()));
                  //connect(Ooo, SIGNAL(statusRead(int,int)), this, SLOT(onRead(int,int)));
                  forceOptions->start();
                  ui->horizontalScrollBar->setEnabled(false);

                  //////////////////////////////////////////////////////
                  int subject_id = query.value(4).toInt();
                  QModelIndexList subjectID_result = subject_model->match(subject_model->index(0, 1), Qt::EditRole, subject_id, 1, Qt::MatchExactly);
                  m_subjectID = subjectID_result.value(0).row(); // might be -1
                  ui->combo_subject->setCurrentIndex(m_subjectID);

                  int teststyle_id = query.value(5).toInt();
                  QModelIndexList teststyleID_result = subject_model->match(subject_model->index(0, 1), Qt::EditRole, teststyle_id, 1, Qt::MatchExactly);
                  m_teststyleID = teststyleID_result.value(0).row(); // might be -1
                  ui->combo_teststyle->setCurrentIndex(m_teststyleID);
                  ///////////////////////////////////////////////////////
                  //shwo answer
                  this->ShowAnswer(query.value(3).toInt());

        }
        ui->statusBar->showMessage(tr("题目ID:")+query.value(0).toString(), 2000);

    }
}

void MainWindow::on_horizontalScrollBar_valueChanged(int i)
{
   // this->ShowQuestion(ui->horizontalScrollBar->value());
   // m_query->seek()
    ui->lblNumber->setText(QString("%1").arg(i));

   if (!m_bScrollBarStoped)
        return;

    if (m_query->seek(i-1,false))
    {
    m_iRecordCurrentID=m_query->value(0).toInt();
    this->ShowQuestion(m_iRecordCurrentID);
    }

    qDebug()<<"value changed"<<m_iRecordCurrentID;
}




void MainWindow::on_horizontalScrollBar_sliderPressed()
{
    m_bScrollBarStoped=false;

}
void MainWindow::on_horizontalScrollBar_sliderReleased()
{
    m_bScrollBarStoped=true;
    int i=ui->horizontalScrollBar->value();
    on_horizontalScrollBar_valueChanged(i);
}

void MainWindow::on_actionAddItem_triggered()
{

    QSqlQuery newquery;
    newquery.prepare(QString("insert into test (question,options) values(null,null)"));
    if(!newquery.exec())
    {
    qDebug()<<"[insert error]";
    }
    else
    {
    qDebug()<<"[insert ok]\n"<<newquery.lastInsertId().toInt();
    }
   m_iRecordCurrentID=newquery.lastInsertId().toInt();
    qDebug()<<"new recordid"<<m_iRecordCurrentID;
    if (FreshtestID())
        qDebug()<<"fresh sucess.";
    else
        qDebug()<<"fresh false.";

    ui->horizontalScrollBar->setMaximum(m_iRecordAmount);
    ui->horizontalScrollBar->setValue(m_iRecordAmount);
    //ShowQuestion(m_iRecordCurrentID);
}

void MainWindow::on_actionDeleteItem_triggered()
{
    QSqlQuery newquery;
    newquery.prepare(QString("delete from test where ID=%1").arg(m_iRecordCurrentID));
    if(!newquery.exec())
    {
    qDebug()<<"[delete failed]";
    }
    else
    {
    qDebug()<<"[delete ok]\n"<<newquery.lastInsertId().toInt();
    }
   //m_iRecordCurrentID=newquery.lastInsertId().toInt();
   // qDebug()<<"recordid"<<recordID;
    if (FreshtestID())
    {
        qDebug()<<"fresh sucess.";
        ui->horizontalScrollBar->setMaximum(m_iRecordAmount);
        ui->horizontalScrollBar->setValue(ui->horizontalScrollBar->value()-1);
        if (m_query->seek(ui->horizontalScrollBar->value()-1,false))
        {
        m_iRecordCurrentID=m_query->value(0).toInt();
        this->ShowQuestion(m_iRecordCurrentID);
        }

    }
    else
    {
        qDebug()<<"fresh false or empty dataset.";
        ui->horizontalScrollBar->setMaximum(0);
        ui->horizontalScrollBar->setValue(0);
        ShowQuestion(-1);
     }

    qDebug()<<"cmddel";

}


void MainWindow::drawDoc()
{
    /* remote image is loading after ..... */
    if (Ooo) {
        ui->textEdit->setDocument ( Ooo->document()->clone() );
        delete Ooo;
        }

        if (forceQuestion) {
            forceQuestion->quit();
        }
}

void MainWindow::drawOptions()
{
    /* remote image is loading after ..... */
    if (OOoptions) {
        ui->textEditOptions->setDocument ( OOoptions->document()->clone() );
        delete OOoptions;
        }

        if (forceOptions) {
            forceOptions->quit();
            ui->horizontalScrollBar->setEnabled(true);
        }
}

void MainWindow::on_combo_teststyle_currentIndexChanged ( int index )
{
    //teststyle_model;
    //int salary = model.data(model.index(4, 2)).toInt();
    m_teststyleID=teststyle_model->data(teststyle_model->index(index,1)).toInt();
    qDebug()<<m_teststyleID;


}

void MainWindow::on_combo_subject_currentIndexChanged ( int index )
{
    //teststyle_model;
    //int salary = model.data(model.index(4, 2)).toInt();

    m_subjectID=subject_model->data(subject_model->index(index,1)).toInt();
    qDebug()<<m_subjectID;

}


void MainWindow::on_actionPaperScope_triggered()
{
    w=new Wizard();
    w->setModal(true);
    w->show();
}

void MainWindow::on_actionTest_triggered()
{
    qDebug()<<"action test";
    test=new testDialog();
    test->setModal(true);
    test->show();
}

void MainWindow::ShowAnswer(int iAnswer)
{


    //int iAnswer=m_testquery->value(2).toInt();
    qDebug()<<"iAnswer"<<iAnswer;

    switch(iAnswer)
    {
        case 1: ui->radioButtonA->setChecked(true);break;
        case 2: ui->radioButtonB->setChecked(true);break;
        case 3: ui->radioButtonC->setChecked(true);break;
        case 4: ui->radioButtonD->setChecked(true);break;
        case 5: ui->radioButtonE->setChecked(true);break;
    default:
        ui->radioButtonHide->setChecked(true);break;
    }

}

void MainWindow::UpdateItemAnswer(int iAnswer)
{
    QSqlQuery query(QString("update test set answer=%1 WHERE ID=%2")
                                            .arg(iAnswer)
                                            .arg(m_iRecordCurrentID));





}

void MainWindow::on_radioButtonA_clicked(bool checked)
{
     if (checked)
     {
         UpdateItemAnswer(1);
         qDebug()<<"on_radioButtonA_toggled";
     }

}

void MainWindow::on_radioButtonB_clicked(bool checked)
{
     if (checked)
     {
         UpdateItemAnswer(2);
         qDebug()<<"on_radioButtonB_toggled";
     }

}
void MainWindow::on_radioButtonC_clicked(bool checked)
{
     if (checked)
     {
         UpdateItemAnswer(3);
         qDebug()<<"on_radioButtonC_toggled";
     }

}
void MainWindow::on_radioButtonD_clicked(bool checked)
{
     if (checked)
     {
         UpdateItemAnswer(4);
         qDebug()<<"on_radioButtonD_toggled";
     }

}
void MainWindow::on_radioButtonE_clicked(bool checked)
{
     if (checked)
     {
         UpdateItemAnswer(5);
         qDebug()<<"on_radioButtonE_toggled";
     }

}
